import axios from 'axios'

let global = {}
let CONTEXT_PATH = ""
let PUBLIC_KEY = ''
let RANDOMKEY = ''

global.setPublicKey = function (value) {
	PUBLIC_KEY = value
}
/**
 * 获取随机AES key
 */
global.getRandomAesKey = function () {
	if (RANDOMKEY == '') {
		let keyArray = []
		for (let i=0; i < 4; i++) {
			keyArray.push((((1+Math.random())*0x10000)|0).toString(16).substring(1))
		}
		RANDOMKEY = keyArray.join('')
		console.log(`Generate AES key is ${RANDOMKEY}`)
	}
	return RANDOMKEY
}
/**
 * 获取RSA公钥
 */
global.getPublicKey = function () {
	return PUBLIC_KEY
}
global.getDebug = function () {
	return DEBUG
}
/**
 * 是否开启DEBUG模式
 */
global.setDebug = function (value) {
	DEBUG = value
}

global.setContextPath = function (value) {
	CONTEXT_PATH = value
}
/**
 * 获取请求context_path
 */
global.getContextPath = function () {
	return CONTEXT_PATH
}
global.getEnv = function () {
  let env = 'development'
  if (process.env.NODE_ENV) {
    env = process.env.NODE_ENV
  }
  return env
}


global.init = function () {
  return new Promise((resolve, reject) => {
		let env = this.getEnv();
		axios.get(`static/config/config-${env}.json`).then((res) => {
			let params = res.data;
			// CONTEXT PATH for axios.
			if (params['CONTEXT_PATH']) {
				this.setContextPath(params['CONTEXT_PATH'])
			}
			// DEBUG mode for JS_SDK
			if(params['JS_SDK_DEBUG']) {
				this.setJsSDKDebug(params['JS_SDK_DEBUG'])
			}
			// 是否开启调试模式
			if(params['DEBUG'] != null) {
				this.setDebug(params['DEBUG'])
			}
			// RSA公钥获取
			if(params['PUBLIC_KEY'] != null) {
				this.setPublicKey(params['PUBLIC_KEY'])
			}
			resolve(true)
		}).catch((err) => {
			console.error('global init err', err);
			reject(true);
		});
	})
}
export default global

